<template>
  <div class="admin-login">
    <div class="login-container">
      <div class="login-header">
        <h1>{{ isLogin ? "管理后台登录" : "注册" }}</h1>
        <p>FAIR plus机器人全产业链接会管理系统</p>
      </div>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        class="login-form"
        @submit.prevent="handleSubmit"
      >
        <el-form-item prop="userCode">
          <el-input
            v-model="formData.userCode"
            placeholder="请输入用户账号"
            size="large"
            prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="userPassword">
          <el-input
            v-model="formData.userPassword"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <!-- 注册时显示的额外字段 -->
        <template v-if="!isLogin">
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="formData.confirmPassword"
              type="password"
              placeholder="请再次确认密码"
              size="large"
              prefix-icon="Lock"
              clearable
              show-password
            />
          </el-form-item>

          <el-form-item prop="userName">
            <el-input
              v-model="formData.userName"
              placeholder="请输入用户名称"
              size="large"
              prefix-icon="User"
              clearable
            />
          </el-form-item>

          <el-form-item prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入手机号（可选）"
              size="large"
              prefix-icon="Phone"
              clearable
            />
          </el-form-item>

          <el-form-item prop="roleId">
            <!-- 隐藏的input用于表单验证 -->
            <input
              v-model="formData.roleId"
              type="hidden"
              @blur="validateRole"
              @change="validateRole"
            />
            <!-- 自定义下拉框 -->
            <div class="custom-select" @click="toggleDropdown">
              <div
                class="select-input"
                :class="{ 'has-error': roleValidationError }"
              >
                <span v-if="selectedRole" class="selected-text">{{
                  selectedRole.roleName
                }}</span>
                <span v-else class="placeholder-text">请选择角色类型</span>
                <i class="arrow" :class="{ 'arrow-up': isDropdownOpen }">▼</i>
              </div>
              <div v-if="isDropdownOpen" class="dropdown-menu">
                <div
                  v-for="role in roleList"
                  :key="role.roleId"
                  class="dropdown-item"
                  @click.stop="selectRole(role)"
                >
                  {{ role.roleName }}
                </div>
                <div
                  v-if="roleList.length === 0"
                  class="dropdown-item disabled"
                >
                  暂无角色数据
                </div>
              </div>
            </div>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-btn"
            :loading="loading"
            @click="handleSubmit"
          >
            {{ isLogin ? "登录" : "注册" }}
          </el-button>
        </el-form-item>

        <div class="login-footer">
          <el-checkbox v-if="isLogin" v-model="rememberMe">记住我</el-checkbox>
          <!-- <div class="auth-switch">
            <a href="#" @click.prevent="toggleMode">
              {{ isLogin ? "没有账号？去注册" : "已有账号？去登录" }}
            </a>
          </div> -->
          <a v-if="isLogin" href="#" @click.prevent="forgotPassword"
            >忘记密码？</a
          >
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  computed,
  onMounted,
  nextTick,
  watch,
  shallowRef,
  triggerRef,
  onBeforeMount,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { User, Lock, Phone } from "@element-plus/icons-vue";
import { authApi } from "@/api/admin";

const router = useRouter();
const formRef = ref();

// 控制登录/注册模式
const isLogin = ref(true);
const loading = ref(false);
const rememberMe = ref(false);

// 表单数据
const formData = reactive({
  userCode: "",
  userPassword: "",
  userName: "",
  confirmPassword: "",
  phone: "",
  roleId: "",
});

// 确保表单数据不会变成数组
const resetFormData = () => {
  formData.userCode = "";
  formData.userPassword = "";
  formData.userName = "";
  formData.confirmPassword = "";
  formData.phone = "";
  formData.roleId = "";
};

// 角色列表 - 使用 shallowRef 避免深层响应式问题
const roleList = shallowRef([]);

// 自定义下拉框状态
const isDropdownOpen = ref(false);
const selectedRole = ref(null);
const roleValidationError = ref(false);

// 表单验证规则 - 使用静态规则避免数组问题
const loginRules = {
  userCode: [
    { required: true, message: "请输入用户账号", trigger: "blur" },
    { min: 3, message: "用户账号长度不能少于3位", trigger: "blur" },
  ],
  userPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
};

const registerRules = {
  userCode: [
    { required: true, message: "请输入用户账号", trigger: "blur" },
    { min: 3, message: "用户账号长度不能少于3位", trigger: "blur" },
  ],
  userPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  userName: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
  confirmPassword: [
    { required: true, message: "请再次确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.userPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  roleId: [{ required: true, message: "请选择角色类型", trigger: "change" }],
};

// 当前使用的验证规则
const formRules = computed(() => {
  return isLogin.value ? loginRules : registerRules;
});

// 加载角色列表
const loadRoleList = async () => {
  try {
    const response = await authApi.getRoleList({
      roleName: "",
      roleType: "",
    });

    if (response && (response.code === "200" || response.code === 200)) {
      const roles = response.data || [];
      roleList.value = [...roles];
      triggerRef(roleList);
    }
  } catch (error) {
    ElMessage.error("加载角色列表失败");
  }
};

// 自定义下拉框操作
const toggleDropdown = () => {
  isDropdownOpen.value = !isDropdownOpen.value;
  // 如果打开下拉框且没有角色数据，尝试加载
  if (isDropdownOpen.value && roleList.value.length === 0) {
    loadRoleList();
  }
};

const selectRole = (role) => {
  selectedRole.value = role;
  formData.roleId = role.roleId;
  isDropdownOpen.value = false;
  roleValidationError.value = false;

  // 手动触发表单验证更新
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate("roleId");
      // 触发隐藏input的change事件
      const hiddenInput = document.querySelector('input[type="hidden"]');
      if (hiddenInput) {
        hiddenInput.dispatchEvent(new Event("change"));
        hiddenInput.dispatchEvent(new Event("blur"));
      }
    }
  });
};

// 角色验证
const validateRole = () => {
  if (!formData.roleId) {
    roleValidationError.value = true;
  } else {
    roleValidationError.value = false;
  }
};

// 点击外部关闭下拉框
const closeDropdown = () => {
  isDropdownOpen.value = false;
};

// 切换登录/注册模式
const toggleMode = async () => {
  // 先清除验证状态
  if (formRef.value) {
    formRef.value.clearValidate();
  }

  // 切换模式
  isLogin.value = !isLogin.value;

  // 强制重置表单数据为字符串
  formData.userCode = "";
  formData.userPassword = "";
  formData.userName = "";
  formData.confirmPassword = "";
  formData.phone = "";
  formData.roleId = "";

  // 重置自定义下拉框状态
  selectedRole.value = null;
  isDropdownOpen.value = false;
  roleValidationError.value = false;

  // 等待DOM更新
  await nextTick();

  // 再次清除验证（确保新规则生效）
  if (formRef.value) {
    formRef.value.clearValidate();
  }

  // 如果切换到注册模式，加载角色列表
  if (!isLogin.value) {
    await loadRoleList();
  }
};

// 处理登录
const handleLogin = async () => {
  try {
    const loginData = {
      userCode: formData.userCode,
      userPassword: formData.userPassword,
      userType: "admin", // 管理员类型
      roleTemplate: "admin", // 管理员角色模板
    };

    const response = await authApi.login(loginData);
    console.log("登录响应:", response);

    if (response && response.code === "200") {
      // 后端登录接口返回的是 UserToken 对象，只包含 token 字段
      const loginResponseData = response.data || {};
      console.log("登录数据:", loginResponseData);
      const token = loginResponseData.token;

      // 验证必要数据
      if (!token) {
        ElMessage.error("登录响应数据异常：缺少token");
        return;
      }

      // 保存token
      localStorage.setItem("adminToken", token);

      // 获取用户完整信息
      try {
        const userInfoResponse = await authApi.getUserInfo(token);
        if (userInfoResponse && userInfoResponse.code === "200") {
          const completeUserInfo = userInfoResponse.data || {};

          // 确保用户信息不为空
          if (completeUserInfo && Object.keys(completeUserInfo).length > 0) {
            localStorage.setItem("adminUser", JSON.stringify(completeUserInfo));
            localStorage.setItem(
              "adminPermissions",
              JSON.stringify(completeUserInfo)
            );
            localStorage.setItem(
              "adminUserInfo",
              JSON.stringify(completeUserInfo)
            );
          } else {
            // 如果用户信息为空，设置基本的用户信息
            const basicUserInfo = {
              userCode: formData.userCode,
              userType: "admin",
              permissions: ["all"],
              roles: ["admin"],
            };
            localStorage.setItem("adminUser", JSON.stringify(basicUserInfo));
            localStorage.setItem(
              "adminPermissions",
              JSON.stringify(basicUserInfo)
            );
            localStorage.setItem(
              "adminUserInfo",
              JSON.stringify(basicUserInfo)
            );
          }
        } else {
          console.warn("获取用户完整信息失败:", userInfoResponse);
          // 设置基本的用户信息
          const basicUserInfo = {
            userCode: formData.userCode,
            userType: "admin",
            permissions: ["all"],
            roles: ["admin"],
          };
          localStorage.setItem("adminUser", JSON.stringify(basicUserInfo));
          localStorage.setItem(
            "adminPermissions",
            JSON.stringify(basicUserInfo)
          );
          localStorage.setItem("adminUserInfo", JSON.stringify(basicUserInfo));
        }
      } catch (err) {
        console.warn("获取用户信息失败:", err);
        // 设置基本的用户信息
        const basicUserInfo = {
          userCode: formData.userCode,
          userType: "admin",
          permissions: ["all"],
          roles: ["admin"],
        };
        localStorage.setItem("adminUser", JSON.stringify(basicUserInfo));
        localStorage.setItem("adminPermissions", JSON.stringify(basicUserInfo));
        localStorage.setItem("adminUserInfo", JSON.stringify(basicUserInfo));
      }

      ElMessage.success("登录成功");
      router.push("/admin/dashboard");
    } else {
      ElMessage.error(response?.message || "登录失败");
    }
  } catch (error) {
    console.error("登录失败:", error);
    ElMessage.error("登录失败: " + (error.message || "网络错误"));
  }
};

// 处理注册
const handleRegister = async () => {
  try {
    const registerData = {
      userCode: formData.userCode,
      userPassword: formData.userPassword,
      userName: formData.userName,
      phone: formData.phone || "",
      roleId: formData.roleId,
    };

    const response = await authApi.register(registerData);

    if (response && response.code === "200") {
      ElMessage.success("注册成功，请登录");
      // 切换到登录模式
      isLogin.value = true;
      // 保留账号和密码
      const { userCode, userPassword } = formData;
      Object.keys(formData).forEach((key) => {
        formData[key] = "";
      });
      formData.userCode = userCode;
      formData.userPassword = userPassword;
    } else {
      ElMessage.error(response?.message || "注册失败");
    }
  } catch (error) {
    console.error("注册失败:", error);
    ElMessage.error("注册失败: " + (error.message || "网络错误"));
  }
};

// 统一提交处理
const handleSubmit = async () => {
  if (!formRef.value) return;

  // 提交前确保表单数据格式正确
  Object.keys(formData).forEach((key) => {
    if (Array.isArray(formData[key])) {
      formData[key] = formData[key][0] || "";
    }
  });

  try {
    await formRef.value.validate();
    loading.value = true;

    if (isLogin.value) {
      await handleLogin();
    } else {
      await handleRegister();
    }
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    loading.value = false;
  }
};

// 忘记密码
const forgotPassword = () => {
  ElMessage.info("请联系系统管理员重置密码");
};

// 组件挂载时初始化
onMounted(async () => {
  // 强制重置所有表单字段为字符串
  formData.userCode = "";
  formData.userPassword = "";
  formData.userName = "";
  formData.phone = "";
  formData.roleId = "";

  // 重置自定义下拉框状态
  selectedRole.value = null;
  isDropdownOpen.value = false;
  roleValidationError.value = false;

  // 等待DOM更新
  await nextTick();

  // 清除所有验证状态
  if (formRef.value) {
    formRef.value.clearValidate();
  }

  // 预加载角色列表
  await loadRoleList();
});

// 添加全局点击事件监听器
onMounted(() => {
  document.addEventListener("click", (e) => {
    const customSelect = document.querySelector(".custom-select");
    if (customSelect && !customSelect.contains(e.target)) {
      closeDropdown();
    }
  });
});

onBeforeMount(() => {
  const lang = localStorage.getItem("user_lang");
  if (lang === "english") {
    window.translate.changeLanguage("chinese_simplified");
    window.translate.selectLanguageTag.languages = "chinese_simplified";
  }
});

// 监听表单数据变化 - 实时修复数组问题
watch(
  formData,
  (newVal, oldVal) => {
    // 检查并修复数组字段
    Object.keys(newVal).forEach((key) => {
      if (Array.isArray(newVal[key])) {
        // 立即修复为字符串
        const fixedValue = newVal[key].length > 0 ? newVal[key][0] || "" : "";
        // 使用 nextTick 确保响应式更新
        nextTick(() => {
          formData[key] = fixedValue;
        });
      }
    });
  },
  {
    deep: true,
    immediate: false,
    flush: "sync",
  }
);

// 监听密码变化，重新验证确认密码
watch(
  () => formData.userPassword,
  (newPassword, oldPassword) => {
    if (oldPassword && formData.confirmPassword && formRef.value) {
      // 当原密码改变时，重新验证确认密码
      nextTick(() => {
        formRef.value.validateField("confirmPassword");
      });
    }
  }
);
</script>

<style scoped>
.admin-login {
  min-height: 50vh;
  background: linear-gradient(135deg, #320063 0%, #4a0a8a 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  animation: fadeIn 0.01s ease-in-out;
  will-change: opacity;
  transform: translateZ(0);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-container {
  background: white;
  border-radius: 15px;
  padding: 30px;
  width: 100%;
  max-width: 400px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 20px;
}

.login-header h1 {
  font-size: 24px;
  color: #2c3e50;
  margin-bottom: 8px;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-form {
  margin-top: 20px;
}

.login-form .el-form-item {
  margin-bottom: 18px;
}

/* 自定义下拉框样式 */
.custom-select {
  position: relative;
  width: 100%;
}

.select-input {
  width: 100%;
  height: 40px;
  padding: 0 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  transition: border-color 0.2s ease;
}

.select-input:hover {
  border-color: #c0c4cc;
}

.select-input:focus {
  border-color: #409eff;
  outline: none;
}

.select-input.has-error {
  border-color: #f56c6c;
}

.select-input.has-error:hover {
  border-color: #f56c6c;
}

.selected-text {
  color: #606266;
  font-size: 14px;
}

.placeholder-text {
  color: #c0c4cc;
  font-size: 14px;
}

.arrow {
  color: #c0c4cc;
  font-size: 12px;
  transition: transform 0.2s ease;
}

.arrow-up {
  transform: rotate(180deg);
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 200px;
  overflow-y: auto;
}

.dropdown-item {
  padding: 8px 12px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.dropdown-item:hover {
  background-color: #f5f7fa;
}

.dropdown-item.disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.dropdown-item.disabled:hover {
  background-color: transparent;
}

.login-btn {
  width: 100%;
  height: 50px;
  font-size: 16px;
  background: linear-gradient(135deg, #320063 0%, #4a0a8a 100%);
  border: none;
}

.login-btn:hover {
  background: linear-gradient(135deg, #4a0a8a 0%, #320063 100%);
}

.login-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  font-size: 14px;
  flex-wrap: wrap;
  gap: 10px;
}

.auth-switch {
  flex: 1;
  text-align: center;
}

.login-footer a {
  color: #320063;
  text-decoration: none;
}

.login-footer a:hover {
  text-decoration: underline;
}

@media (max-width: 480px) {
  .login-container {
    padding: 30px 20px;
  }

  .login-header h1 {
    font-size: 24px;
  }
}
</style>
